package com.hc.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.print.attribute.standard.MediaSize.Other;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hc.domain.ResourcesPic;
import com.hc.service.IResourcesPicService;
import com.hc.util.FileUtils;
import com.hc.util.HeaderUtil;
import com.hc.util.IdWorker;
import com.hc.util.LoggerUtil;
import com.hc.util.OtherUtils;

import javassist.compiler.SyntaxError;

@Controller
@RequestMapping(value = "File")
public class FileUtilsController extends BaseController {
	@Resource
	private IResourcesPicService resourcesPicService;

	/**
	 * 
	 * @Description： 上传图片
	 * 
	 * @param files
	 * @param request
	 * @return
	 * @author:
	 * @since: 2017年5月19日 上午10:41:12
	 */
	@RequestMapping("/upload")
	@ResponseBody
	public JSON threeFileUpload(@RequestParam("file") CommonsMultipartFile files[], HttpServletRequest req) {
		JSONArray keyArr = new JSONArray();
		FileOutputStream fos = null;
		InputStream in = null;
		File f = new File(FILE_PATH);
		if (!f.exists()) {
			f.mkdirs();
		}
		for (int i = 0; i < files.length; i++) {
			if (!files[i].isEmpty()) {
				String newFileName = IdWorker.createId();
				try {
					fos = new FileOutputStream(FILE_PATH + newFileName);
					in = files[i].getInputStream();
					int b = 0;
					while ((b = in.read()) != -1) {
						fos.write(b);
					}
				} catch (Exception e) {
					LoggerUtil.error(e);
				} finally {
					try {
						if (fos != null) {
							fos.close();
						}
						if (in != null) {
							in.close();
						}
					} catch (Exception e2) {
						LoggerUtil.error(e2);
					}
				}
				keyArr.add(newFileName);
			}
		}
		return Message(SUCCESS, "上传成功", keyArr);
	}

	/**
	 * 
	 * @Description： 上传图片
	 * 
	 * @param files
	 * @param request
	 * @return
	 * @author:
	 * @since: 2017年5月19日 上午10:41:12
	 */
	@RequestMapping("/uploadPics")
	@ResponseBody
	public JSON FileUploadPics(@RequestParam("imgFile") MultipartFile file, HttpServletRequest req) {
		String ext = "gif,jpg,jpeg,png,bmp";
		String path = req.getContextPath();
		String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/";
		JSONObject obj = new JSONObject();
		FileOutputStream fos = null;
		InputStream in = null;
		File f = new File(FILE_PATH + "KingEditor/");
		if (!f.exists()) {
			f.mkdirs();
		}
		if (!file.isEmpty()) {
			String newFileName = IdWorker.createId();
			try {
				fos = new FileOutputStream(FILE_PATH + "KingEditor/" + newFileName);
				in = file.getInputStream();
				String fileExt = FileUtils.getFileTypeByStream(IOUtils.toByteArray(file.getInputStream()));
				if (isEmpty(fileExt)||ext.indexOf(fileExt)<0) {
					obj.put("error", 1);
					obj.put("message", "未知图片类型（合法格式:PNG/JPEG/JPG/GIF/BMP）");
					return obj;
				}
				int b = 0;
				while ((b = in.read()) != -1) {
					fos.write(b);
				}
			} catch (Exception e) {
				LoggerUtil.error(e);
			} finally {
				try {
					if (fos != null) {
						fos.close();
					}
					if (in != null) {
						in.close();
					}
				} catch (Exception e2) {
					LoggerUtil.error(e2);
				}
			} /**/
			obj.put("error", 0);
			obj.put("url", basePath + "File/getFile/" + "KingEditor/" + newFileName);
			return obj;
		}
		obj.put("error", 1);
		obj.put("message", "图片添加失败");
		return obj;
	}

	/**
	 * 
	 * @Description： 获取图片文件
	 * 
	 * @param req
	 * @param resp
	 * @param key
	 * @author:
	 * @since: 2017年5月19日 上午10:40:45
	 */
	@RequestMapping("/getFile/{type}/{key}")
	public void getFile(HttpServletRequest req, HttpServletResponse resp, @PathVariable String type,
			@PathVariable String key) {
		FileInputStream in = null;
		OutputStream out = null;
		try {
			File file = new File(FILE_PATH + type + "/" + key);
			if (!file.exists()) {
				return;
			}
			in = new FileInputStream(FILE_PATH + type + "/" + key);
			out = resp.getOutputStream();
			byte buffer[] = new byte[1024];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			LoggerUtil.error(e);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				LoggerUtil.error(e);
			}
		}
	}

	/**
	 * 
	 * @Description： 上传单个图片文件
	 * 
	 * @param resp
	 * @param req
	 * @param type
	 *            图片类型（非后缀类型，该类型表明图片用于何处）
	 * @param file
	 *            文件
	 * @return
	 * @author:
	 * @since: 2017年8月24日 上午11:54:31
	 */
	@ResponseBody
	@RequestMapping(value = "/settingHeadImg/{type}", method = RequestMethod.POST)
	public JSON uploadPicResource(HttpServletResponse resp, HttpServletRequest req, @PathVariable String type,
			@RequestParam(value = "file", required = true) MultipartFile file,
			@RequestParam(value = "link", required = false) String link,
			@RequestParam(value = "title", required = true) String title) {
		if (isEmpty(type)) {
			return Message(ERROR, "未指定图片上传类型", null);
		}
		String ext = "gif,jpg,jpeg,png,bmp";
		String path = req.getContextPath();
		String basePath = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + path + "/";
		String newFileName = IdWorker.createId();
		FileOutputStream fos = null;
		InputStream in = null;
		File f = new File(FILE_PATH + type);
		if (!f.exists()) {
			f.mkdirs();
		}
		if (file.isEmpty()) {
			return Message(ERROR, "请选择文件", null);
		}
		try {
			fos = new FileOutputStream(FILE_PATH + type + "/" + newFileName);
			in = file.getInputStream();
			String fileExt = FileUtils.getFileTypeByStream(IOUtils.toByteArray(file.getInputStream()));
			if (isEmpty(fileExt) || ext.indexOf(fileExt) < 0) {
				return Message(ERROR, "未知图片类型（合法格式:PNG/JPEG/JPG/GIF/BMP）", null);
			}
			/*
			 * if ((in.available() / 1024) > 153600) { return Message(ERROR,
			 * "上传文件大小超过限制（150KB）", null); }
			 */
			int b = 0;
			while ((b = in.read()) != -1) {
				fos.write(b);
			}
			String url = basePath + "File/getFile/" + type + "/" + newFileName;
			ResourcesPic resPic = new ResourcesPic();
			resPic.setCreateDate(OtherUtils.getCurrentDate());
			resPic.setLink(link);
			resPic.setSort(0);
			resPic.setStatus(0);
			resPic.setTitle(title);
			resPic.setType(type);
			resPic.setPath(url);
			resourcesPicService.save(resPic);
			return Message(SUCCESS, "添加服务成功", url);
		} catch (Exception e) {
			return LoggerUtil.logInfo(e, "添加服务异常");
		} finally {
			try {
				if (fos != null) {
					fos.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				LoggerUtil.error(e2);
			}
		}
	}
}
